import axios from 'axios'
import { ElMessage } from 'element-plus'

// 创建axios实例
const api = axios.create({
  baseURL: '/api/rpa',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 创建权限相关的API实例
const authApi = axios.create({
  baseURL: '/api/auth',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 响应拦截器
api.interceptors.response.use(
  response => {
    const { code, message, data } = response.data
    if (code === 200) {
      return data
    } else {
      ElMessage.error(message || '请求失败')
      return Promise.reject(new Error(message || '请求失败'))
    }
  },
  error => {
    ElMessage.error(error.message || '请求失败')
    return Promise.reject(error)
  }
)

// 权限API响应拦截器
authApi.interceptors.response.use(
  response => {
    const { code, message, data } = response.data
    if (code === 200) {
      return data
    } else {
      ElMessage.error(message || '权限验证失败')
      return Promise.reject(new Error(message || '权限验证失败'))
    }
  },
  error => {
    ElMessage.error(error.message || '权限验证失败')
    return Promise.reject(error)
  }
)

/**
 * 通用API调用服务
 * 提供模拟API调用功能，统一API请求和响应处理
 */
export default {
  // 应用管理
  getApps() {
    return api.get('/apps')
  },
  
  viewApp(id) {
    return api.post('/apps/view', { id })
  },
  
  editApp(app) {
    return api.post('/apps/edit', app)
  },

  // 任务管理
  getTasks() {
    return api.get('/tasks')
  },
  
  viewTask(id) {
    return api.post('/tasks/view', { id })
  },
  
  editTask(task) {
    return api.post('/tasks/edit', task)
  },
  
  stopTask(id, name) {
    return api.post('/tasks/stop', { id, name })
  },

  // 机器人管理
  getRobots() {
    return api.get('/robots')
  },
  
  viewRobot(id) {
    return api.post('/robots/view', { id })
  },
  
  editRobot(robot) {
    return api.post('/robots/edit', robot)
  },
  
  connectRobot(id, name) {
    return api.post('/robots/connect', { id, name })
  },
  
  restartRobot(id, name) {
    return api.post('/robots/restart', { id, name })
  },

  // 权限管理
  getRoles() {
    return authApi.get('/roles')
  },
  
  getUserRoles(userId) {
    return authApi.post('/users/roles', { userId })
  },
  
  getUsers() {
    return authApi.get('/users')
  },
  
  checkPermission(userId, permission) {
    return authApi.post('/permissions/check', { userId, permission })
  },

  // 通用API调用方法
  async callApi(action, params, onSuccess, onError) {
    try {
      let response
      switch (action) {
        // 应用相关
        case '查看应用详情':
          response = await this.viewApp(params.id)
          break
        case '编辑应用':
        case '添加应用':
          response = await this.editApp(params)
          break
          
        // 任务相关
        case '查看任务详情':
          response = await this.viewTask(params.id)
          break
        case '编辑任务':
        case '新建任务':
          response = await this.editTask(params)
          break
        case '停止任务':
          response = await this.stopTask(params.id, params.name)
          break
          
        // 机器人相关
        case '查看机器人详情':
          response = await this.viewRobot(params.id)
          break
        case '编辑机器人':
        case '添加机器人':
          response = await this.editRobot(params)
          break
        case '连接机器人':
          response = await this.connectRobot(params.id, params.name)
          break
        case '重启机器人':
          response = await this.restartRobot(params.id, params.name)
          break
        
        // 权限相关
        case '获取角色列表':
          response = await this.getRoles()
          break
        case '获取用户角色':
          response = await this.getUserRoles(params.userId)
          break
        case '获取用户列表':
          response = await this.getUsers()
          break
        case '检查权限':
          response = await this.checkPermission(params.userId, params.permission)
          break
          
        default:
          throw new Error(`未知的操作类型: ${action}`)
      }
      
      onSuccess?.({
        success: true,
        message: response.message || '操作成功',
        data: response
      })
    } catch (error) {
      onError?.(error)
      ElMessage.error(error.message || '操作失败')
    }
  }
} 